package io.renren.handler;


import cn.hutool.core.collection.CollUtil;
import io.renren.builder.TextBuilder;
import io.renren.core.config.ProjectConStant;
import io.renren.entity.Book;
import io.renren.entity.BookVideo;
import io.renren.entity.UserDefaultInfo;
import io.renren.entity.WxUser;
import io.renren.service.BookVideoService;
import io.renren.service.UserDefaultInfoService;
import io.renren.service.WxUserService;
import io.renren.utils.ConfigConstant;
import io.renren.utils.QrLogicUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Slf4j
@Component
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private BookVideoService bookVideoService;

    @Autowired
    private UserDefaultInfoService userDefaultInfoService;

    @Autowired
    private VideoHandleUtils videoHandleUtils;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context,
                                    WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        log.info("新关注用户 OPENID: " + wxMessage.getFromUser());

        // 获取微信用户基本信息
        WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);

        if (userWxInfo == null) {
            return null;
        }
        //查询数据库是否存在
        Map query = new HashMap();
        // query.put("openId", userWxInfo.getOpenId());
        query.put("unionId",userWxInfo.getUnionId());
        List<WxUser> list = wxUserService.queryList(query);
        WxUser wxUser = null;
        if (CollUtil.isEmpty(list)) {
            wxUser = new WxUser();
            //创建用户,保存到数据库
            wxUser.setStatus("0");
            wxUser.setSubscribe("1");
            wxUser.setSubscribeTime(new Date());
            wxUser.setOpenId(userWxInfo.getOpenId());
            wxUser.setUnionId(userWxInfo.getUnionId());
            wxUser.setImgUrl(userWxInfo.getHeadImgUrl());
            wxUser.setGradeId(Long.parseLong(ConfigConstant.DEFAULT_GRADE_ID));
            wxUser.setNickName(userWxInfo.getNickname());
            wxUser.setSubscribeScene(userWxInfo.getSubscribeScene());
            wxUser.setQrSceneStr("0".equals(userWxInfo.getQrScene()) ? userWxInfo.getQrSceneStr() :
                    userWxInfo.getQrScene());
            wxUserService.save(wxUser);
        } else {
            wxUser = list.get(0);
            wxUser.setSubscribe("1");
            wxUser.setUpdateTime(new Date());
            wxUser.setSubscribeTime(new Date());
            wxUser.setOpenId(userWxInfo.getOpenId());
            wxUser.setUnionId(userWxInfo.getUnionId());
            wxUser.setImgUrl(userWxInfo.getHeadImgUrl());
            wxUser.setNickName(userWxInfo.getNickname());
            wxUser.setSubscribeScene(userWxInfo.getSubscribeScene());
            // 如果之前为空，则更新
            if (StringUtils.isEmpty(wxUser.getQrSceneStr())) {
                wxUser.setQrSceneStr("0".equals(userWxInfo.getQrScene()) ? userWxInfo.getQrSceneStr() :
                        userWxInfo.getQrScene());
            }
            wxUserService.update(wxUser);
        }

        WxMpXmlOutMessage responseResult = handleVideo(wxMessage, weixinService);

        if (responseResult != null) {
            return responseResult;
        }

        return new TextBuilder().build("感谢关注", wxMessage, weixinService);

    }

    private WxMpXmlOutMessage handleVideo(WxMpXmlMessage wxMessage, WxMpService wxMpService) {
        if (StringUtils.isBlank(wxMessage.getEventKey())) {
            return null;
        }
        String eventKey = wxMessage.getEventKey().replace("qrscene_", "");
        return videoHandleUtils.getVideoListWxMpXmlOutMessage(wxMessage, wxMpService, eventKey);
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage, WxMpService wxMpService, Long userId) {
        if (StringUtils.isBlank(wxMessage.getEventKey())) {
            return null;
        }

        if (wxMessage.getEventKey().replace("qrscene_", "").startsWith(ProjectConStant.EXAM_PAPER_QR_CODE_PREFIX)) {
            return null;
        }

        WxMpXmlOutNewsMessage.Item item1 = FengDiUtils.dealFengDi(wxMessage.getEventKey());
        if (item1 != null) {
            WxMpXmlOutNewsMessage newsMessage = WxMpXmlOutMessage.NEWS()
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser())
                    .addArticle(item1)
                    .build();
            log.info("响应的图文消息为：" + newsMessage.toString());
            return newsMessage;
        }
        //根据二维码编号获取视频列表
        Map query = new HashMap();
        //query.put("status", "1");
        query.put("deleted", "0");
        query.put("qrcodeNo", wxMessage.getEventKey());

        //获取视频信息
        List<BookVideo> bookVideoList = bookVideoService.queryList(query);
        if (bookVideoList == null || bookVideoList.size() == 0) {
            String qrDesc = QrLogicUtil.getQrDesc4YS(wxMessage.getEventKey().replace("qrscene_", ""));
            // return new TextBuilder().build(qrDesc, wxMessage, wxMpService);
            if (StringUtils.isNotBlank(qrDesc)) {
                return new TextBuilder().build(qrDesc, wxMessage, wxMpService);
            } else {
                return null;
            }
        }

        List<WxMpXmlOutNewsMessage.Item> collect = bookVideoList.stream()
                .filter(bookVideo -> "0".equals(bookVideo.getBook().getDeleted()))
                .sorted(Comparator.comparing(BookVideo::getPageNo).thenComparing(BookVideo::getOrderField))
                .map(bookVideo -> {
                    WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
                    item.setDescription("立即点击查看内容");
                    item.setTitle(bookVideo.getVideoName());
                    item.setUrl(ConfigConstant.BASE_URL + "/api/video_detail.html?videoId=" + bookVideo.getId() +
                            "&userFrom=1");
                    item.setPicUrl(StringUtils.isEmpty(bookVideo.getBook().getCoverUrl()) ?
                            ConfigConstant.DEFAULT_BOOK_COVER : bookVideo.getBook().getCoverUrl());
                    return item;
                })
                .collect(Collectors.toList());
        WxMpXmlOutNewsMessage.Item[] items = new WxMpXmlOutNewsMessage.Item[collect.size()];
        WxMpXmlOutNewsMessage newsMessage = WxMpXmlOutMessage.NEWS()
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .addArticle(collect.toArray(items))
                .build();
        log.info("响应的图文消息为：" + newsMessage.toString());

        //设置默认信息设置
        BookVideo video = bookVideoList.stream()
                .filter(bookVideo -> "0".equals(bookVideo.getBook().getDeleted()))
                .findFirst().orElse(null);
        if (video != null) {

            Book book = video.getBook();
            setDefaultInfo(book.getGradeId(), book.getSubjectId(), book.getVersionId(), userId);
        }

        return newsMessage;
    }

    private void setDefaultInfo(Long gradeId, Long subjectId, Long versionId, Long userId) {
        Map query = new HashMap();
        query.put("userId", userId);
        query.put("gradeId", gradeId);
        query.put("subjectId", subjectId);
        List<UserDefaultInfo> userDefaultInfoList = userDefaultInfoService.queryList(query);
        UserDefaultInfo userDefaultInfo = new UserDefaultInfo();
        //如果没有则创建
        if (userDefaultInfoList == null || userDefaultInfoList.size() == 0) {
            userDefaultInfo.setUserId(userId);
            userDefaultInfo.setGradeId(gradeId);
            userDefaultInfo.setSubjectId(subjectId);
            userDefaultInfo.setVersionId(versionId);
            userDefaultInfo.setSeasonId(Long.parseLong(ConfigConstant.DEFAULT_SEASON_ID));
            userDefaultInfoService.save(userDefaultInfo);
        } else {
            //否则更新
            userDefaultInfo = userDefaultInfoList.get(0);
            userDefaultInfo.setGradeId(gradeId);
            userDefaultInfo.setSubjectId(subjectId);
            userDefaultInfo.setVersionId(versionId);
            userDefaultInfo.setUpdateTime(new Date());
            userDefaultInfoService.update(userDefaultInfo);
        }
    }

}
